﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Runtime.InteropServices;
using System.Text;
using SmallERP.COM;
using SmallERP.DAL;
using SmallERP.MODEL.FenPian;
using System.IO;
using SmallERP.MODEL.FoundationModel;
using System.Drawing;
using System.ServiceModel;
using Smallerp.Contracts;
using System.Data;
using Smallerp.Contracts.DataContracts;

namespace SmallERP.Bll.PinBan
{
    public class ImportPhotoBLL
    {
        public delegate string TellView(string str, Color color);
        public delegate string TellView1(string str);
        public delegate void   ProgressDelegate(int p);
        

        //ChannelFactory<IOperateDB> _proxyOperatrDB;
        IOperateDB _OperateDb;
        public ImportPhotoBLL(IOperateDB inOper)
        {
            //_proxyOperatrDB = new ChannelFactory<IOperateDB>("IOperateDB");
            _OperateDb = inOper;
        }
        public string GetOrderRootDir()
        {
            string rtnPath = "";
            //using (smallerpDataContext db = new smallerpDataContext())
            //{

            //    rtnPath = db.SysSetting.FirstOrDefault().SysOrderPath;
            //}
            DataTable table = _OperateDb.QueryDataTable("select * from SysSetting");
            if (table.Rows.Count > 0)
            {
                rtnPath = table.Rows[0]["SysOrderPath"].ToString();
            }

            return rtnPath;
        }
        /// <summary>
        /// 向数据库添加数据
        /// </summary>
        /// <param name="inView"></param>
        /// <returns></returns>
        public int AddOrderToDB(Smallerp.Contracts.DataContracts.OrderViewDCT inView)
        {
            //try
            //{


            //    using (smallerpDataContext db = new smallerpDataContext())
            //    {
            //        orderInfo checkOrder = db.orderInfo.FirstOrDefault(p => p.OrderName == inView.OrderName && p.OrilOrderPath == inView.OrilOrderPath);
            //        if (checkOrder != null)
            //        {
            //            return -1;
            //        }
            //        int intNum = inView.ProductNum;
            //        while (intNum > 0)
            //        {
            //            orderInfo order = new orderInfo();
            //            if (inView.ProductNum > 1)
            //            {
            //                order.OrderName = inView.OrderName + "（" + intNum + "）";
            //            }
            //            else
            //            {
            //                order.OrderName = inView.OrderName;
            //            }
            //            order.OrderPath = inView.OrderPath;
            //            order.PaperFaceId = inView.PaperFace.PaperFaceId;
            //            order.PaperTypeId = inView.PaperTypeInfo.PaperTypeId;
            //            order.Priority = inView.Priority;
            //            order.ProductNum = 1;
            //            order.Remark = inView.Remark;
            //            order.SameFlagOrderId = 0; //由份数决定
            //            order.StartTime = Com.UnityMethod.GetSystemTime();
            //            order.CompleteTime = Com.UnityMethod.GetSystemTime();
            //            order.Status = (int)Status.OrderStatus.WaitMove;
            //            order.OrilOrderPath = inView.OrilOrderPath;
            //            List<photoInfo> photoInfos = new List<photoInfo>();
            //            photoInfo info;
            //            foreach (PhotoView list in inView.PhotoS)
            //            {
            //                info = new photoInfo();
            //                info.Height = list.Height;
            //                info.IsClearBox = false;
            //                info.IsReback = false;
            //                info.orderInfo = order;
            //                info.PhotoName = list.PhotoName;
            //                info.PicPath = list.PicPath;
            //                info.PixHeight = list.PixHeight;
            //                info.PixWidth = list.PixWidth;
            //                info.PicOripath = list.PicOripath;
            //                info.PrinterId = list.PrinterId;
            //                info.Remark = list.Remark == null ? " " : list.Remark;
            //                info.SameFlagPhotoId = 0; //份数决定
            //                info.Status = (int)Status.PhotoStatus.WaitMove;
            //                info.TotalNum = list.TotalNum;
            //                info.Width = list.Width;

            //            }
            //            db.AddToorderInfo(order);
            //            intNum--;
            //        }

            //        db.SaveChanges();
            //    }
            //}
            //catch (Exception)
            //{

            //    return -1;
            //}
            return _OperateDb.AddOrderToDB(inView);

        }
        /// <summary>
        /// 向数据库添加数据
        /// </summary>
        /// <param name="inView"></param>
        /// <returns></returns>
        public int AddOrderToDB(Smallerp.Contracts.DataContracts.OrderViewDCT inView,bool isFouce)
        {
           
            return _OperateDb.AddOrderToDB2(inView,Convert.ToInt32(isFouce));

        }
        /// <summary>
        /// 向数据库添加数据
        /// </summary>
        /// <param name="inView"></param>
        /// <returns></returns>
        public int AddOrderToDBMoveBefore(Smallerp.Contracts.DataContracts.OrderViewDCT inView, bool isFouce)
        {

            return _OperateDb.AddOrderToDB2MoveBefore(inView, Convert.ToInt32(isFouce));

        }
        /// <summary>
        /// 检查重复
        /// </summary>
        /// <param name="inView"></param>
        /// <returns></returns>
        public bool CheckOrder(OrderViewDCT inView)
        {
            //orderInfo oi;
            ////using (smallerpDataContext db = new smallerpDataContext())
            ////{
            ////    oi = db.orderInfo.FirstOrDefault(p => p.OrderName == inView.OrderName);

            ////}

            //if (oi == null)
            //{
            //    return false;
            //}
            //else
            //{
            //    return true;
            //}
            string queryOrder = "select * from orderinfo where ordername='" + inView.OrderName + "'";
            DataTable qTable = _OperateDb.QueryDataTable(queryOrder);
            if (qTable.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 检查重复
        /// </summary>
        /// <param name="inView"></param>
        /// <returns></returns>
        public bool CheckOrder(string orderName)
        {
            //orderInfo oi;
            ////using (smallerpDataContext db = new smallerpDataContext())
            ////{
            ////    oi = db.orderInfo.FirstOrDefault(p => p.OrderName == inView.OrderName);

            ////}

            //if (oi == null)
            //{
            //    return false;
            //}
            //else
            //{
            //    return true;
            //}
            string queryOrder = "select * from orderinfo where ordername='" + orderName + "'";
            DataTable qTable = _OperateDb.QueryDataTable(queryOrder);
            if (qTable.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 移动文件，文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <param name="flag">1如果文件存在，则替换；2如移动到不同的卷，则复制文件并删除原来的文件；3移动操作在系统重启后才真正执行</param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "MoveFileEx", CharSet = CharSet.Unicode)]
        public static extern bool MoveFile(string src, string dst, long flag);



        public event TellView Tel;
        public event TellView1 TelOrderID;
        public event TellView1 TelCurrName;
        public event ProgressDelegate ProgressEvent;
        public event TellView1 TelViewPhotoInfo;
        private int intRunStatus = 0;//0可执行，1上次没执行完提前退出
        /// <summary>
        /// 移动照片
        /// </summary>
        /// <returns></returns>
        public int MoveDir()
        {
            int intRtn = 0;
            if (intRunStatus == 1)
            {

                intRtn = 3;//上次没执行完
                return intRtn;
            }
            try
            {
                //using (smallerpDataContext db = new smallerpDataContext())
                //{
                //    intRunStatus = 1;
                //    int waitMove = (int)Status.OrderStatus.WaitMove;
                //    List<orderInfo> orderInfoList = db.orderInfo.Where(p => p.Status == waitMove).ToList();
                //    foreach (orderInfo info in orderInfoList)
                //    {
                //        string temPath = info.OrderPath.Substring(0, info.OrderPath.LastIndexOf("\\"));
                //        if (!Directory.Exists(temPath))
                //        {
                //            Directory.CreateDirectory(temPath);
                //        }
                //        if (!Directory.Exists(info.OrilOrderPath))
                //        {
                //            // inTelfo.Status = (int)Status.OrderStatus.Doing;
                //            if (!Directory.Exists(info.OrderPath))
                //            {
                //                Tel("原文件" + info.OrilOrderPath + "不存在", Color.Black);
                //            }
                //            else
                //            {
                //                info.Status = (int)Status.OrderStatus.Doing;
                //            }
                //            continue;
                //        }

                //        //  bool bo = MoveFile(info.OrilOrderPath, info.OrderPath,2);
                //        //bool bo = MoveFile(@"D:\图片\幼英", @"D:\图片\to\幼英", 2);
                //        try
                //        {
                //            // Tel("正在移动" + info.OrilOrderPath );
                //            if (Directory.Exists(info.OrderPath))
                //            {
                //                DeleteDirectory(info.OrderPath);
                //            }

                //            Directory.Move(info.OrilOrderPath, info.OrderPath);
                //            info.Status = (int)Status.OrderStatus.Doing;

                //        }
                //        catch (Exception exx)
                //        {
                //            if (info.OrilOrderPath.IndexOf(GetOrderRootDir()) == -1)
                //            {
                //                // bool bo = MoveFile(info.OrilOrderPath, info.OrderPath, 2);
                //                Tel("发现非服务器路径，正在从" + info.OrilOrderPath + "拷贝文件....", Color.Black);
                //                CopyFilesDirs(info.OrilOrderPath, info.OrderPath);

                //                try
                //                {
                //                    //Directory.Delete();
                //                    Tel("正在删除" + info.OrilOrderPath, Color.Black);
                //                    DeleteDirectory(info.OrilOrderPath);
                //                }

                //                catch (Exception)
                //                {

                //                    throw;
                //                }
                //            }
                //            else
                //            {
                //                Tel("错误信息：" + exx.Message + "....", Color.Black);
                //            }
                //            // Tel(info.OrderName + "移动成功");
                //            info.Status = (int)Status.OrderStatus.Doing;

                //        }
                //        Tel(info.OrderName + "移动成功", Color.Black);



                //    }
                //    intRunStatus = 0;//改为可执行
                //    intRtn = 0;//当前循环执行完毕
                //    db.SaveChanges();

                //    List<orderInfo> orderInfoListLeft = db.orderInfo.Where(p => p.Status == waitMove).ToList();
                //    if (orderInfoListLeft.Count == 0)
                //    {
                //        // intRunStatus = 0;
                //        intRtn = 0;//无任务
                //    }

                //}
                intRunStatus = 1;
                int waitMove = (int)Status.OrderStatus.WaitMove;
                DataTable WaitMoveTb = _OperateDb.QueryDataTable("select * from orderinfo where status=" + waitMove);
                for (int i = 0; i < WaitMoveTb.Rows.Count; i++)
                {
                    string OrderName = WaitMoveTb.Rows[i]["OrderName"].ToString();
                    string OrderPath = WaitMoveTb.Rows[i]["OrderPath"].ToString();
                    string OrilOrderPath = WaitMoveTb.Rows[i]["OrilOrderPath"].ToString();
                    int OrderProductId = Convert.ToInt32(WaitMoveTb.Rows[i]["OrderProductId"]);
                    string temPath = OrderPath.Substring(0, OrderPath.LastIndexOf("\\"));
                    if (!Directory.Exists(temPath))
                    {
                        Directory.CreateDirectory(temPath);
                    }
                    if (!Directory.Exists(OrilOrderPath))
                    {
                        // inTelfo.Status = (int)Status.OrderStatus.Doing;
                        if (!Directory.Exists(OrderPath))
                        {
                            Tel("原文件" + OrilOrderPath + "不存在", Color.Black);
                        }
                        else
                        {
                            string upSucess = "update orderinfo set status=" + (int)Status.OrderStatus.Doing + " where OrderProductId=" + OrderProductId;
                            _OperateDb.ExecuteNonQuery(upSucess);
                        }
                        continue;
                    }

                    //  bool bo = MoveFile(info.OrilOrderPath, info.OrderPath,2);
                    //bool bo = MoveFile(@"D:\图片\幼英", @"D:\图片\to\幼英", 2);
                    try
                    {
                        // Tel("正在移动" + info.OrilOrderPath );
                        if (Directory.Exists(OrderPath))
                        {
                            DeleteDirectory(OrderPath);
                        }

                        Directory.Move(OrilOrderPath, OrderPath);
                        //info.Status = (int)Status.OrderStatus.Doing;
                        string upSucess = "update orderinfo set status=" + (int)Status.OrderStatus.Doing + " where OrderProductId=" + OrderProductId;
                        _OperateDb.ExecuteNonQuery(upSucess);

                    }
                    catch (Exception exx)
                    {
                        if (OrilOrderPath.IndexOf(GetOrderRootDir()) == -1)
                        {
                            // bool bo = MoveFile(info.OrilOrderPath, info.OrderPath, 2);
                            Tel("发现非服务器路径，正在从" + OrilOrderPath + "拷贝文件....", Color.Black);
                            CopyFilesDirs(OrilOrderPath, OrderPath);

                            try
                            {
                                //Directory.Delete();
                                Tel("正在删除" + OrilOrderPath, Color.Black);
                                DeleteDirectory(OrilOrderPath);
                            }

                            catch (Exception)
                            {

                                throw;
                            }
                        }
                        else
                        {
                            Tel("错误信息：" + exx.Message + "....", Color.Black);
                        }
                        // Tel(info.OrderName + "移动成功");
                        string upSucess = "update orderinfo set status=" + (int)Status.OrderStatus.Doing + " where OrderProductId=" + OrderProductId;
                        _OperateDb.ExecuteNonQuery(upSucess);

                    }
                    Tel(OrderName + "移动成功", Color.Black);



                }
                intRunStatus = 0;//改为可执行
                intRtn = 0;//当前循环执行完毕
                //db.SaveChanges();

                //List<orderInfo> orderInfoListLeft = db.orderInfo.Where(p => p.Status == waitMove).ToList();
                //if (orderInfoListLeft.Count == 0)
                //{
                //    // intRunStatus = 0;
                //    intRtn = 0;//无任务
                //}
            }



            catch
            {
                intRtn = 0;
            }
            return intRtn;

        }
        /// <summary>
        /// 整个文件夹拷贝
        /// </summary>
        /// <param name="yanfilepath">源</param>
        /// <param name="mudifilepath">目标</param>
        private void CopyFilesDirs(string yanfilepath, string mudifilepath)
        {
            try
            {
                string[] arrDirs = Directory.GetDirectories(yanfilepath);
                string[] arrFiles = Directory.GetFiles(yanfilepath);
                if (arrFiles.Length != 0)
                {
                    for (int i = 0; i < arrFiles.Length; i++)
                        File.Copy(yanfilepath + "\\" + Path.GetFileName(arrFiles[i]), mudifilepath + "\\"
                        + Path.GetFileName(arrFiles[i]), true);
                    File.Delete(yanfilepath);
                }
                if (arrDirs.Length != 0)
                {
                    for (int i = 0; i < arrDirs.Length; i++)
                    {
                        Directory.CreateDirectory(mudifilepath + "\\" + Path.GetFileName(arrDirs[i]));
                        //递归调用   
                        Tel("正在移动" + yanfilepath + "文件夹", Color.Black);
                        CopyFilesDirs(yanfilepath + "\\" + Path.GetFileName(arrDirs[i]),
                        mudifilepath + "\\" + Path.GetFileName(arrDirs[i]));
                        //File.Delete(yanfilepath);
                    }
                }
                else
                    return;
            }
            catch (Exception ex)
            {
                Tel("错误信息：" + ex.Message + "....", Color.Black);
            }
        }

        static void DeleteDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length == 0)
                {
                    if (Directory.Exists(dir))
                    {
                        Directory.Delete(dir);
                    }
                    return;
                }
                else if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length != 0)
                {
                    string[] strFiles = Directory.GetFiles(dir);
                    foreach (string str in strFiles)
                    {
                        if (str.ToUpper().IndexOf(("Thumbs.db").ToUpper()) >= 0)
                        {
                            File.Delete(str);
                        }
                        if (str.ToUpper().EndsWith("TXT"))
                        {
                            File.Delete(str);

                        }
                    }
                }

                foreach (string var in Directory.GetDirectories(dir))
                {

                    DeleteDirectory(var);
                }
                foreach (string var in Directory.GetFiles(dir))
                {
                    if (File.Exists(var))
                    {
                        File.Delete(var);
                    }
                    //File.Delete(var);
                }
                if (Directory.Exists(dir))
                {
                    Directory.Delete(dir);
                }
            }
            // Directory.Delete(dir);
        }

        //bool CheckIntegrality(orderInfo inor, List<photoInfo> inlist)
        //{
        //    //orderInfo inOrder = inor;
        //    //if (Directory.Exists(inOrder.OrilOrderPath))
        //    //{

        //    //    foreach (photoInfo info in inlist)
        //    //    {
        //    //        if (!File.Exists(info.PicOripath))
        //    //        {
        //    //            if (!File.Exists(info.PicPath))
        //    //            {
        //    //                info.Remark += "照片不存在";
        //    //                return false;
        //    //            }
        //    //        }

        //    //    }
        //    //    return true;

        //    //}
        //    //else
        //    //{
        //    //    if (Directory.Exists(inOrder.OrderPath))//多分时 后面处理这里不做处理
        //    //    {
        //    //        return true;
        //    //    }
        //    //    else
        //    //    {
        //    //        inor.Remark += "目录不存在";
        //    //        return false;
        //    //    }
        //    //}
        //    return true;
        //}

        /// <summary>
        /// 移动照片 以照片为单位u
        /// </summary>
        /// <returns></returns>
        public int MoveDirPhoto()
        {
            int intRtn = 0;
            if (intRunStatus == 1)
            {

                intRtn = 3;//上次没执行完
                return intRtn;
            }
            try
            {
               

                int waitMove = (int)Status.OrderStatus.WaitMove;
                DataTable WaitMoveTb = _OperateDb.QueryDataTable("select * from orderinfo where status=" + waitMove);
                int WaitMoveTbRowCount=WaitMoveTb.Rows.Count;
                float iProgressValue = 0;
                int orderStep = 100 / (WaitMoveTbRowCount == 0 ? 1 : WaitMoveTbRowCount);
                for (int i = 0; i < WaitMoveTbRowCount; i++)
                {
                    string OrderName = WaitMoveTb.Rows[i]["OrderName"].ToString();
                    string OrderPath = WaitMoveTb.Rows[i]["OrderPath"].ToString();
                    string OrilOrderPath = WaitMoveTb.Rows[i]["OrilOrderPath"].ToString();
                    int OrderProductId = Convert.ToInt32(WaitMoveTb.Rows[i]["OrderProductId"]);

                    TelCurrName(OrderName);

                   

                    string CurrPhotos = "select * from photoinfo where orderproductid=" + OrderProductId;
                    DataTable PhotosQuery = _OperateDb.QueryDataTable(CurrPhotos);
                    string CurrMovedPhotos = "select * from photoinfo where orderproductid=" + OrderProductId + " and status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                    DataTable PhotosMovedQuery = _OperateDb.QueryDataTable(CurrMovedPhotos);
                    if (PhotosMovedQuery.Rows.Count == PhotosQuery.Rows.Count)
                    {
                        string upDoingstr = "update orderinfo set status=" + (int)Status.OrderStatus.Doing + " where orderproductid=" + OrderProductId;
                        int aaa=_OperateDb.ExecuteNonQuery(upDoingstr);
                        TelOrderID(OrderName);
                        DeleteDirectory(OrilOrderPath);
                        iProgressValue += orderStep;
                        ProgressEvent((int)iProgressValue);
                        continue;
                    }

                    Tel("正在复制文件夹【" + OrderName+"】", Color.Green);
                    int PhotosQueryRowCount=PhotosQuery.Rows.Count;

                    float photoStep = orderStep / (float)(PhotosQueryRowCount == 0 ? 1 : PhotosQueryRowCount);
                    for (int j = 0; j < PhotosQueryRowCount; j++)
                    {
                        iProgressValue += photoStep;
                        ProgressEvent((int)iProgressValue);
                        string PicPath = PhotosQuery.Rows[j]["PicPath"].ToString();
                        string PicOripath = PhotosQuery.Rows[j]["PicOripath"].ToString();
                        int photoid = Convert.ToInt32(PhotosQuery.Rows[j]["photoid"]);
                        int photostatus = Convert.ToInt32(PhotosQuery.Rows[j]["status"]);
                        string temPhotoPath = PicPath.Substring(0, PicPath.LastIndexOf("\\"));
                        string photoName = PhotosQuery.Rows[j]["PhotoName"].ToString();
                        TelViewPhotoInfo(photoName);
                        if (!Directory.Exists(temPhotoPath))
                        {
                            try
                            {
                                Directory.CreateDirectory(temPhotoPath);
                            }
                            catch (Exception ex)
                            {
                                Tel("创建文件目录错误：" + temPhotoPath + "   错误信息：" + ex.Message, Color.Red);
                            }
                        }

                        if (!File.Exists(PicOripath))
                        {
                            if (!File.Exists(PicPath))
                            {
                                Tel("错误信息：原文件" + PicPath + "不存在,请找到此文件，然后从错误列表中删除该产品后重新导片！", Color.Red);
                                //pi.Status = (int)Status.PhotoStatus.PhotoNotExists;
                                int rtnErrorder = _OperateDb.ExecuteNonQuery("update orderinfo set status=" + (int)Status.OrderStatus.ErrorBeforeMove + " where orderproductid=" + OrderProductId);
                                int rtnErrphoto = _OperateDb.ExecuteNonQuery("update photoinfo set status=" + (int)Status.PhotoStatus.PhotoNotExists + " where photoid=" + photoid);
                                //info.Status = (int)Status.OrderStatus.ErrorBeforeMove;
                                goto bc;
                            }
                            else
                            {
                                if (photostatus != (int)Status.PhotoStatus.WaitPB)
                                {
                                    //pi.Status = (int)Status.PhotoStatus.WaitPB;
                                    int rtnSucessphoto = _OperateDb.ExecuteNonQuery("update photoinfo set status=" + (int)Status.PhotoStatus.WaitPB + " where photoid=" + photoid);
                                }
                                continue;
                            }

                        }
                       
                        
                        try
                        {
                            //Tel("正在移动" + list.PicOripath);
                            //File.Move(list.PicOripath, list.PicPath);                    
                            try
                            {
                                //if (File.Exists(PicPath))
                                //{
                                //    FileInfo fileEx = new FileInfo(PicPath);
                                //    fileEx.Attributes = FileAttributes.Normal;
                                //    File.Delete(PicPath);
                                //}
                              
                            }
                            catch (Exception)
                            {
                                Tel("系统信息：文件已经存在，请先删除文件:" + PicPath, Color.Red);
                                continue;
                            }

                            FileInfo file = new FileInfo(PicOripath);
                            file.Attributes = FileAttributes.Normal;

                            bool moveStatus = false;
                            if (!File.Exists(PicPath))
                            {
                                moveStatus = MoveFile(PicOripath, PicPath, 2);
                            }
                            else
                            {
                                moveStatus = true;
                            }
                            if (moveStatus)
                            {
                                if (File.Exists(PicPath))
                                {
                                    //pi.Status = (int)Status.PhotoStatus.WaitPB;
                                    int rtnSucessphoto = _OperateDb.ExecuteNonQuery("update photoinfo set status=" + (int)Status.PhotoStatus.WaitPB + " where photoid=" + photoid);
                                }

                                else
                                {
                                    Tel("系统信息：文件剪切失败,将再次移动", Color.Green);
                                    continue;
                                }
                            }
                            else
                            {
                                Tel("系统信息：文件剪切失败,将再次移动", Color.Green);
                                continue;
                            }

                        }
                        catch (Exception exServerFileMove)
                        {
                            Tel("系统信息：文件剪切失败,将再次移动，" + exServerFileMove.Message, Color.Green);
                            continue;

                        }
                   
                        //}

                        //检查产品是否完成移动
                        //List<photoInfo> photoCheck = info.photoInfo.Where(p => p.Status != (int)Status.PhotoStatus.WaitPB).ToList();
                        string PhotoCheck = "select * from photoinfo where orderproductid=" + OrderProductId + " and status =" + (int)Status.PhotoStatus.WaitMove;
                        DataTable PCheck = _OperateDb.QueryDataTable(PhotoCheck);
                        if (PCheck.Rows.Count == 0)
                        {
                            //List<string> fileList = new List<string>();
                            //List<string> ImgList = new List<string>();
                            //GetAllPicByDir(OrilOrderPath, ImgList);
                            //GetAllNoPicByDir(OrilOrderPath, fileList);

                            //if (ImgList.Count > 0)
                            //{
                            //    Tel("提醒信息：" + OrilOrderPath + "文件夹内还有未导入的照片，请查看", Color.YellowGreen);
                            //}
                            //else if (fileList.Count > 0)
                            //{
                            //    Tel("提醒信息：" + OrilOrderPath + "文件夹内发现非图片格式的文件，请查看", Color.YellowGreen);
                            //}
                            //else//原文件夹中没有任何文件时则可以删除原目录
                            //{
                            //    try
                            //    {
                            //        DeleteDirectory(OrilOrderPath);
                            //    }
                            //    catch
                            //    {
                            //        Tel("提醒信息：" + OrilOrderPath + "无法删除该目录，请手动删除", Color.YellowGreen);
                            //    }
                            //}

                            //info.Status = (int)Status.OrderStatus.Doing;
                            int rtnErrorder = _OperateDb.ExecuteNonQuery("update orderinfo set status=" + (int)Status.OrderStatus.Doing + " where orderproductid=" + OrderProductId);
                            DeleteDirectory(OrilOrderPath);
                            Tel("文件夹【" + OrderName + "】处理完成", Color.Green);
                            TelViewPhotoInfo("处理完成");
                            TelOrderID(OrderName.ToString());
                        }
                    }
                bc:
                    ;
                }
            }
            catch (Exception ex)
            {
                Tel("错误信息：" + ex.Message, Color.Black);
                intRunStatus = 0;
                return 0;
            }
            return intRtn;

        }




        /// <summary>
        /// 递归找到文件夹下所有照片文件
        /// </summary>
        /// <param name="inPath"></param>
        /// <param name="inList"></param>
        public void GetAllPicByDir(string inPath, List<string> inList)
        {
            string picTag = ".JPEG.JPG.TIF.BMP.TIFF";
            DirectoryInfo rootDir = new DirectoryInfo(inPath);
            if (rootDir.Exists)
            {
                FileInfo[] fileList = rootDir.GetFiles();
                foreach (FileInfo info in fileList)
                {
                    if (picTag.Contains(info.Extension.ToUpper()))
                    {
                        inList.Add(info.FullName);
                    }
                }
                DirectoryInfo[] listDir = rootDir.GetDirectories();
                foreach (DirectoryInfo dir in listDir)
                {
                    GetAllPicByDir(dir.FullName, inList);
                }
            }

        }

        /// <summary>
        /// 递归找到文件夹下所有照片文件
        /// </summary>
        /// <param name="inPath"></param>
        /// <param name="inList"></param>
        public void GetAllNoPicByDir(string inPath, List<string> inList)
        {
            string picTag = ".JPEG.JPG.TIF.BMP.TIFF";
            DirectoryInfo rootDir = new DirectoryInfo(inPath);
            if (rootDir.Exists)
            {
                FileInfo[] fileList = rootDir.GetFiles();
                foreach (FileInfo info in fileList)
                {
                    if (!picTag.Contains(info.Extension.ToUpper()))
                    {
                        //Tel(info.FullName);
                        //除了txt和thumbs.db文件这两种文件系统删除 其余系统不自动删除
                        if (info.FullName.ToUpper().IndexOf(("Thumbs.db").ToUpper()) == -1 && !info.FullName.ToUpper().EndsWith("TXT"))
                        {
                            //Tel(info.FullName);
                            inList.Add(info.FullName);
                        }


                    }
                }
                DirectoryInfo[] listDir = rootDir.GetDirectories();
                foreach (DirectoryInfo dir in listDir)
                {
                    GetAllPicByDir(dir.FullName, inList);
                }
            }

        }
        /// <summary>
        /// 导片未完成列表
        /// </summary>
        /// <returns></returns>
        public List<OrderViewDCT> GetUnMoveView()
        {
            List<OrderViewDCT> unMoveList = new List<OrderViewDCT>();
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    int unMove = (int)Status.OrderStatus.WaitMove;
            //    OrderView view;
            //    List<orderInfo> orderInfos = db.orderInfo.Where(P => P.Status == unMove).ToList();
            //    foreach (orderInfo list in orderInfos)
            //    {
            //        view = new OrderView();
            //        view.OrderName = list.OrderName;
            //        view.OrderPath = list.OrderPath;
            //        view.OrderProductId = list.OrderProductId;
            //        view.OrilOrderPath = list.OrilOrderPath;
            //        view.CompleteTime = list.CompleteTime;
            //        list.photoInfo.Load();
            //        List<photoInfo> photoList = list.photoInfo.ToList();
            //        List<PhotoView> photoViews = new List<PhotoView>();
            //        PhotoView photo;
            //        foreach (photoInfo pit in photoList)
            //        {
            //            photo = new PhotoView()
            //            {
            //                Height = pit.Height,
            //                IsReback = pit.IsReback,
            //                OrderProductId = list.OrderProductId,
            //                PhotoId = pit.PhotoId,
            //                PhotoName = pit.PhotoName,
            //                PicPath = pit.PicPath,
            //                PixHeight = pit.PixWidth,
            //                PixWidth = pit.PixWidth,
            //                Remark = pit.Remark,
            //                SameFlagPhotoId = pit.SameFlagPhotoId,
            //                Status = pit.Status,
            //                TotalNum = 1,//份数
            //                Width = pit.Width,
            //                UserId = pit.userId,
            //                PrinterId = pit.PrinterId,
            //                //IsClearBox = pit.IsClearBox
            //            };
            //            photoViews.Add(photo);
            //        }
            //        view.PhotoS = photoViews;
            //        PaperFace face = db.PaperFace.FirstOrDefault(p => p.PaperFaceId == list.PaperFaceId);
            //        if (face != null)
            //        {
            //            view.PaperFace = new PaperFace_Info() { PaperFaceId = face.PaperFaceId, PaperFaceName = face.PaperFaceName };

            //        }
            //        else
            //        {
            //            view.PaperFace = new PaperFace_Info();

            //        }
            //        PaperType type = db.PaperType.FirstOrDefault(p => p.PaperTypeId == list.PaperTypeId);
            //        if (type != null)
            //        {
            //            view.PaperTypeInfo = new PaperType_Info() { PaperTypeId = type.PaperTypeId, PaperTypeName = type.PaperTypeName };

            //        }
            //        else
            //        {
            //            view.PaperTypeInfo = new PaperType_Info();
            //        }
            //        view.Priority = list.Priority;
            //        view.ProductNum = list.ProductNum;
            //        view.Remark = list.Remark;
            //        view.StartTime = list.StartTime;
            //        view.Status = list.Status;
            //        unMoveList.Add(view);
            //        view.PrintInfo = new Printer_info();
            //        //view.
            //    }

            //}
            int unMove = (int)Status.OrderStatus.WaitMove;
            string UnMoveSql = "select * from orderinfo where status=" + unMove;
            DataTable TableOrder = _OperateDb.QueryDataTable(UnMoveSql);
            OrderViewDCT view;
            for (int i = 0; i < TableOrder.Rows.Count; i++)
            {
                view = new OrderViewDCT();
                view.OrderName = TableOrder.Rows[i]["OrderName"].ToString();

                view.OrderPath = TableOrder.Rows[i]["OrderPath"].ToString();
                view.OrderProductId = Convert.ToInt32(TableOrder.Rows[i]["OrderProductId"]);
                view.OrilOrderPath = Convert.ToString(TableOrder.Rows[i]["OrilOrderPath"]);
                view.CompleteTime = Convert.ToDateTime(TableOrder.Rows[i]["CompleteTime"]);
                view.PhotoS = new List<PhotoDCT>();

                string PhotoSql = "select * from photoinfo where orderproductid=" + view.OrderProductId;
                DataTable TablePhotos = _OperateDb.QueryDataTable(PhotoSql);
                for (int j = 0; j < TablePhotos.Rows.Count; j++)
                {
                    PhotoDCT photo = new PhotoDCT();
                    photo.Height = Convert.ToDouble(TablePhotos.Rows[j]["Height"]);
                    photo.IsReback = Convert.ToBoolean(TablePhotos.Rows[j]["IsReback"]);
                    photo.OrderProductId = Convert.ToInt32(TablePhotos.Rows[j]["OrderProductId"]);
                    photo.PhotoId = Convert.ToInt32(TablePhotos.Rows[j]["PhotoId"]);
                    photo.PhotoName = Convert.ToString(TablePhotos.Rows[j]["PhotoName"]);
                    photo.PicPath = Convert.ToString(TablePhotos.Rows[j]["PicPath"]);
                    photo.PixHeight = Convert.ToInt32(TablePhotos.Rows[j]["PixHeight"]);
                    photo.PixWidth = Convert.ToInt32(TablePhotos.Rows[j]["PixWidth"]);
                    photo.Remark = Convert.ToString(TablePhotos.Rows[j]["Remark"]);
                    photo.SameFlagPhotoId = Convert.ToInt32(TablePhotos.Rows[j]["SameFlagPhotoId"]);
                    photo.Status = Convert.ToInt32(TablePhotos.Rows[j]["Status"]);
                    photo.TotalNum = Convert.ToInt32(TablePhotos.Rows[j]["TotalNum"]);
                    photo.Width = Convert.ToDouble(TablePhotos.Rows[j]["Width"]);
                    photo.UserId = Convert.ToInt32(TablePhotos.Rows[j]["UserId"]);
                    photo.PrinterId = Convert.ToInt32(TablePhotos.Rows[j]["PrinterId"]);
                    view.PhotoS.Add(photo);

                }
                string QueryPaperType = "select * from papertype where PaperTypeId=" + Convert.ToUInt32(TableOrder.Rows[i]["PaperTypeId"]);
                DataTable PaperTypeTable = _OperateDb.QueryDataTable(QueryPaperType);
                if (PaperTypeTable.Rows.Count > 0)
                {
                    view.PaperTypeInfo = new PaperTypeDCT() { PaperTypeId = Convert.ToInt32(PaperTypeTable.Rows[0]["PaperTypeId"]), PaperTypeName = Convert.ToString(PaperTypeTable.Rows[0]["PaperTypeName"]) };
                }
                else
                {
                    view.PaperTypeInfo = new PaperTypeDCT();
                }
                string QueryPaperFace = "Select * from PaperFace where PaperFaceId=" + Convert.ToUInt32(TableOrder.Rows[i]["PaperFaceId"]);
                DataTable PaperFceTable = _OperateDb.QueryDataTable(QueryPaperFace);
                if (PaperTypeTable.Rows.Count > 0)
                {
                    view.PaperFace = new PaperFaceDCT() { PaperFaceId = Convert.ToInt32(PaperFceTable.Rows[0]["PaperFaceId"]), PaperFaceName = Convert.ToString(PaperFceTable.Rows[0]["PaperFaceName"]) };

                }
                else
                {
                    view.PaperFace = new PaperFaceDCT();
                }
                view.Priority = Convert.ToInt32(TableOrder.Rows[i]["Priority"]);
                view.ProductNum = Convert.ToInt32(TableOrder.Rows[i]["ProductNum"]);
                view.Remark = Convert.ToString(TableOrder.Rows[i]["Remark"]);
                view.SameFlagOrderId = Convert.ToInt32(TableOrder.Rows[i]["SameFlagOrderId"]);
                view.StartTime = Convert.ToDateTime(TableOrder.Rows[i]["StartTime"]);
                view.Status = Convert.ToInt32(TableOrder.Rows[i]["Status"]);

                unMoveList.Add(view);
            }

            return unMoveList;
        }
        /// <summary>
        ///  获取移动错误的列表
        /// </summary>
        /// <returns></returns>
        public List<OrderViewDCT> GetMoveErrorView()
        {
            List<OrderViewDCT> unMoveList = new List<OrderViewDCT>();
            int unMove = (int)Status.OrderStatus.ErrorBeforeMove;
            string UnMoveSql = "select * from orderinfo where status=" + unMove;
            DataTable TableOrder = _OperateDb.QueryDataTable(UnMoveSql);
            OrderViewDCT view;
            for (int i = 0; i < TableOrder.Rows.Count; i++)
            {
                view = new OrderViewDCT();
                view.OrderName = TableOrder.Rows[i]["OrderName"].ToString();

                view.OrderPath = TableOrder.Rows[i]["OrderPath"].ToString();
                view.OrderProductId = Convert.ToInt32(TableOrder.Rows[i]["OrderProductId"]);
                view.OrilOrderPath = Convert.ToString(TableOrder.Rows[i]["OrilOrderPath"]);
                view.CompleteTime = Convert.ToDateTime(TableOrder.Rows[i]["CompleteTime"]);
                view.PhotoS = new List<PhotoDCT>();

                string PhotoSql = "select * from photoinfo where orderproductid=" + view.OrderProductId;
                DataTable TablePhotos = _OperateDb.QueryDataTable(PhotoSql);
                for (int j = 0; j < TablePhotos.Rows.Count; j++)
                {
                    PhotoDCT photo = new PhotoDCT();
                    photo.Height = Convert.ToDouble(TablePhotos.Rows[j]["Height"]);
                    photo.IsReback = Convert.ToBoolean(TablePhotos.Rows[j]["IsReback"]);
                    photo.OrderProductId = Convert.ToInt32(TablePhotos.Rows[j]["OrderProductId"]);
                    photo.PhotoId = Convert.ToInt32(TablePhotos.Rows[j]["PhotoId"]);
                    photo.PhotoName = Convert.ToString(TablePhotos.Rows[j]["PhotoName"]);
                    photo.PicPath = Convert.ToString(TablePhotos.Rows[j]["PicPath"]);
                    photo.PixHeight = Convert.ToInt32(TablePhotos.Rows[j]["PixHeight"]);
                    photo.PixWidth = Convert.ToInt32(TablePhotos.Rows[j]["PixWidth"]);
                    photo.Remark = Convert.ToString(TablePhotos.Rows[j]["Remark"]);
                    photo.SameFlagPhotoId = Convert.ToInt32(TablePhotos.Rows[j]["SameFlagPhotoId"]);
                    photo.Status = Convert.ToInt32(TablePhotos.Rows[j]["Status"]);
                    photo.TotalNum = Convert.ToInt32(TablePhotos.Rows[j]["TotalNum"]);
                    photo.Width = Convert.ToDouble(TablePhotos.Rows[j]["Width"]);
                    photo.UserId = Convert.ToInt32(TablePhotos.Rows[j]["UserId"]);
                    photo.PrinterId = Convert.ToInt32(TablePhotos.Rows[j]["PrinterId"]);
                    view.PhotoS.Add(photo);

                }
                string QueryPaperType = "select * from papertype where PaperTypeId=" + Convert.ToUInt32(TableOrder.Rows[i]["PaperTypeId"]);
                DataTable PaperTypeTable = _OperateDb.QueryDataTable(QueryPaperType);
                if (PaperTypeTable.Rows.Count > 0)
                {
                    view.PaperTypeInfo = new PaperTypeDCT() { PaperTypeId = Convert.ToInt32(PaperTypeTable.Rows[0]["PaperTypeId"]), PaperTypeName = Convert.ToString(PaperTypeTable.Rows[0]["PaperTypeName"]) };
                }
                else
                {
                    view.PaperTypeInfo = new PaperTypeDCT();
                }
                string QueryPaperFace = "Select * from PaperFace where PaperFaceId=" + Convert.ToUInt32(TableOrder.Rows[i]["PaperFaceId"]);
                DataTable PaperFceTable = _OperateDb.QueryDataTable(QueryPaperFace);
                if (PaperTypeTable.Rows.Count > 0)
                {
                    view.PaperFace = new PaperFaceDCT() { PaperFaceId = Convert.ToInt32(PaperFceTable.Rows[0]["PaperFaceId"]), PaperFaceName = Convert.ToString(PaperFceTable.Rows[0]["PaperFaceName"]) };

                }
                else
                {
                    view.PaperFace = new PaperFaceDCT();
                }
                view.Priority = Convert.ToInt32(TableOrder.Rows[i]["Priority"]);
                view.ProductNum = Convert.ToInt32(TableOrder.Rows[i]["ProductNum"]);
                view.Remark = Convert.ToString(TableOrder.Rows[i]["Remark"]);
                view.SameFlagOrderId = Convert.ToInt32(TableOrder.Rows[i]["SameFlagOrderId"]);
                view.StartTime = Convert.ToDateTime(TableOrder.Rows[i]["StartTime"]);
                view.Status = Convert.ToInt32(TableOrder.Rows[i]["Status"]);

                unMoveList.Add(view);
            }

            return unMoveList;
        }
        public int DelErrList(List<OrderViewDCT> inList)
        {
            int rtn = 0;
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    foreach (OrderView orderView in inList)
            //    {
            //        orderInfo order = db.orderInfo.FirstOrDefault(p => p.OrderProductId == orderView.OrderProductId);
            //        if (order != null)
            //        {
            //            db.DeleteObject(order);
            //        }
            //    }
            //    db.SaveChanges();
            //    return 0;
            //}
            try
            {
                foreach (OrderViewDCT orderView in inList)
                {
                    string delOrder = "delete from orderinfo where orderproductid=" + orderView.OrderProductId;
                    _OperateDb.ExecuteNonQuery(delOrder);
                }
            }
            catch (Exception ex)
            {
                rtn = -1;
            }


            return rtn;
        }
        public string GetSaveFilePath()
        {
            return _OperateDb.GetFileSavepath();
        }

        /// <summary>
        /// 获取要移动的产品的照片列表
        /// </summary>
        /// <returns></returns>
        public List<OrderInfo_PBDCT> GetMoveFileList()
        {
            List<OrderInfo_PBDCT> MoveList = new List<OrderInfo_PBDCT>();
           
            int photoStatus_PB = (int)SmallERP.COM.Status.PhotoStatus.WaitMove;//拼板中
           

            string QueryOrderForPB = "select * from orderinfo where status=" + 3 + " and orderproductid in (select  distinct orderproductid from photoinfo where status=" + photoStatus_PB + ")";
          

            DataTable TableOrderInfoPB = _OperateDb.QueryDataTable(QueryOrderForPB);

            for (int i = 0; i < TableOrderInfoPB.Rows.Count; i++)
            {
                OrderInfo_PBDCT oi_INfoT = new OrderInfo_PBDCT();
                oi_INfoT.order_Base_Info = new Order_InfoDCT()
                {
                    CompleteTime = Convert.ToDateTime(TableOrderInfoPB.Rows[i]["CompleteTime"]),
                    OrderName = Convert.ToString(TableOrderInfoPB.Rows[i]["OrderName"]),
                    OrderPath = Convert.ToString(TableOrderInfoPB.Rows[i]["OrderPath"]),
                    OrderProductId = Convert.ToInt32(TableOrderInfoPB.Rows[i]["OrderProductId"]),
                    OrilOrderPath = Convert.ToString(TableOrderInfoPB.Rows[i]["OrilOrderPath"]),
                    PaperFaceId = Convert.ToInt32(TableOrderInfoPB.Rows[i]["PaperFaceId"]),
                    PaperTypeId = Convert.ToInt32(TableOrderInfoPB.Rows[i]["PaperTypeId"]),
                    Priority = Convert.ToInt32(TableOrderInfoPB.Rows[i]["Priority"]),
                    ProductNum = Convert.ToInt32(TableOrderInfoPB.Rows[i]["ProductNum"]),
                    Remark = Convert.ToString(TableOrderInfoPB.Rows[i]["Remark"]),
                    SameFlagOrderId = Convert.ToInt32(TableOrderInfoPB.Rows[i]["SameFlagOrderId"]),
                    StartTime = Convert.ToDateTime(TableOrderInfoPB.Rows[i]["StartTime"]),
                    Status = Convert.ToInt32(TableOrderInfoPB.Rows[i]["Status"]),
                    FatherFolder = Convert.ToString(TableOrderInfoPB.Rows[i]["FatherFolder"]),
                    GranddadFolder = Convert.ToString(TableOrderInfoPB.Rows[i]["GranddadFolder"])
                };
                string QuertPhotoForPB = "select * from Photoinfo where orderproductid=" + Convert.ToInt32(TableOrderInfoPB.Rows[i]["OrderProductId"]);
                DataTable tableQueryPhoto = _OperateDb.QueryDataTable(QuertPhotoForPB);
                oi_INfoT.PhotoList = new List<PhotoInfo_PBDCT>();
                
                for (int j = 0; j < tableQueryPhoto.Rows.Count; j++)
                {
                    oi_INfoT.PhotoList.Add(new PhotoInfo_PBDCT()
                    {
                        BarCodeStatus = 0,
                        IsAutoPB = false,
                        IsInBoard = false,
                        IsWhirl = false,
                        Location = new Point(0, 0),
                        OrderName = Convert.ToString(TableOrderInfoPB.Rows[i]["OrderName"]),
                        PaperFaceName = "",
                        PaperTypeName = "",
                        PBNum = 0,
                        Priority = Convert.ToInt32(TableOrderInfoPB.Rows[i]["Priority"]),
                        OrderPhotosCount = 0,
                        OrderPhotosInboardCount =0,
                        Photo_Base_Info = new PhotoDCT()
                        {
                            Height = Convert.ToDouble(tableQueryPhoto.Rows[j]["Height"]),
                            IsClearBox = Convert.ToBoolean(tableQueryPhoto.Rows[j]["IsClearBox"]),
                            IsReback = Convert.ToBoolean(tableQueryPhoto.Rows[j]["IsReback"]),
                            OrderProductId = Convert.ToInt32(TableOrderInfoPB.Rows[i]["OrderProductId"]),
                            PaperFaceId = Convert.ToInt32(TableOrderInfoPB.Rows[i]["PaperFaceId"]),
                            PaperTypeID = Convert.ToInt32(TableOrderInfoPB.Rows[i]["PaperTypeId"]),
                            PhotoId = Convert.ToInt32(tableQueryPhoto.Rows[j]["PhotoId"]),
                            PhotoName = Convert.ToString(tableQueryPhoto.Rows[j]["PhotoName"]),
                            PicOripath = Convert.ToString(tableQueryPhoto.Rows[j]["PicOripath"]),
                            PicPath = Convert.ToString(tableQueryPhoto.Rows[j]["PicPath"]),
                            PixHeight = Convert.ToInt32(tableQueryPhoto.Rows[j]["PixHeight"]),
                            PixWidth = Convert.ToInt32(tableQueryPhoto.Rows[j]["PixWidth"]),
                            PrinterId = Convert.ToInt32(tableQueryPhoto.Rows[j]["PrinterId"]),
                            Remark = Convert.ToString(tableQueryPhoto.Rows[j]["Remark"]),
                            SameFlagPhotoId = Convert.ToInt32(tableQueryPhoto.Rows[j]["SameFlagPhotoId"]),
                            Status = Convert.ToInt32(tableQueryPhoto.Rows[j]["Status"]),
                            TotalNum = Convert.ToInt32(tableQueryPhoto.Rows[j]["TotalNum"]),
                            UserId = Convert.ToInt32(tableQueryPhoto.Rows[j]["UserId"]),
                            Width = Convert.ToDouble(tableQueryPhoto.Rows[j]["Width"]),
                            DPI = Convert.ToInt32(tableQueryPhoto.Rows[j]["DPI"]),
                            ColorType = Convert.ToInt32(tableQueryPhoto.Rows[j]["ColorType"])
                        }

                    });
                    

                }
                //if (oi_INfoT.PhotoList.Count>0)
                if (oi_INfoT.PhotoList.Count > 0)
                {
                    MoveList.Add(oi_INfoT);
                }
            }

            return MoveList;
        }
    }
}
